﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SystemFrameWork;
using SystemFrameWork.Enums;
using Entity.Model;

namespace DutyWeb.Login
{
    public partial class Login : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, ImageClickEventArgs e)
        {
            bool isSuccess = this.IsCheck();
            string userName = this.txtUserName.Text.Trim();
            string password = this.txtPassword.Text.Trim();

            if (isSuccess)
            {
                Sys_User user = base.sys_UserManagement.CheckUser(userName, password);
                if (user != null)
                {
                    this.BindSys_Role(user);
                    this.LoginSystem(user);
                    Response.Redirect("~/Admin/Default.aspx?type=C");

                }
                else
                {
                    base.ShowMessage("用户名或密码错误，请重试！", ExceptionLevel.Info);
                    return;
                }
            }
        }

        private void LoginSystem(Sys_User user)
        {
            try
            {
                user.FunctionRole = base.sys_UserManagement.GetFunctionalModule(user);


                ///place the login result in to cookies
                this.SaveUserToCookie(user.ID.ToString(), user.FunctionRole);
            }
            catch
            {
                this.ShowMessage("操作失败，请联系管理员！", ExceptionLevel.Fatal);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private List<Sys_Role> BindSys_Role(Sys_User user)
        {
            if (user != null)
            {

                List<Sys_Role> roleList = new List<Sys_Role>();
                try
                {
                    roleList = base.sys_RoleManagement.LoadUserGroupByUser(user);
                    if (roleList != null)
                    {
                        base.CurrentRole = roleList;
                        //base.EnableDataPermission = roleList.EnableDataPermission;
                    }
                    else
                    {
                        base.CurrentRole = new List<Sys_Role>();
                        //base.CurrentRole.ID = Guid.Empty;
                    }
                }
                catch
                {
                    this.ShowMessage("发生系统异常，请联系管理员！", ExceptionLevel.Fatal);
                }


                return roleList;
            }
            else
            {
                return null;
            }
        }

        #region Check
        /// <summary>
        /// Check input info
        /// </summary>
        /// <returns>bool</returns>
        private bool IsCheck()
        {
            string userName = this.txtUserName.Text.Trim();
            string password = this.txtPassword.Text.Trim();

            if (string.IsNullOrEmpty(userName))
            {
                ShowMessage("用户名不能为空！", ExceptionLevel.Info);
                this.txtUserName.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(password))
            {
                ShowMessage("密码不能为空！", ExceptionLevel.Info);
                this.txtPassword.Focus();
                return false;
            }

            string checkCode = CheckCode;
            if (string.IsNullOrEmpty(checkCode))
            {
                ShowMessage("验证码不能为空！", ExceptionLevel.Info);
                this.txtCheckCode.Focus();
                return false;
            }

            string checkCodeInput = this.txtCheckCode.Text.Trim();

            if (string.IsNullOrEmpty(checkCodeInput))
            {
                ShowMessage("验证码不能为空！", ExceptionLevel.Info);
                this.txtCheckCode.Focus();
                return false;
            }

            if (checkCodeInput.ToUpper() != checkCode.ToUpper())
            {
                ShowMessage("验证码错误，请重试！", ExceptionLevel.Info);
                return false;
            }

            return true;
        }
        #endregion

        /// <summary>
        /// Save user info to cookie
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="role"></param>
        private void SaveUserToCookie(string userName, string role)
        {
            ///Ticket version
            ///Date/time issued
            ///Username associated with ticket
            ///Date/time to expire
            ///"true" for a persistent user cookie
            ///User-data, in this case the roles
            ///Path cookie valid for
            System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(
       1,
       userName,
       DateTime.Now,
       DateTime.Now.AddMinutes(80),
       false,
       role,
       System.Web.Security.FormsAuthentication.FormsCookiePath);

            /// Encrypt the cookie using the machine key for secure transport
            string hash = System.Web.Security.FormsAuthentication.Encrypt(ticket);

            ///Name of auth cookie 
            ///Hashed ticket
            HttpCookie cookie = new HttpCookie(
                System.Web.Security.FormsAuthentication.FormsCookieName,
                hash);

            ///Set the cookie's expiration time to the tickets expiration time
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }

            ///Add the cookie to the list for outgoing response
            Response.Cookies.Add(cookie);
        }

    }

}
